import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

/**
 * 请求记录接口
 */
export interface RequestLog {
  id: string;
  timestamp: string;
  method: string;
  url: string;
  status: number;
  duration: number;
  headers: { [key: string]: string };
  body: any;
  response: any;
  error?: string;
}

/**
 * 请求统计信息
 */
export interface RequestStats {
  totalRequests: number;
  successRequests: number;
  errorRequests: number;
  averageDuration: number;
  lastRequestTime: string;
}

/**
 * 全局请求记录服务
 * 记录所有通过 MockDataService 的请求，供 UI 展示
 */
@Injectable({
  providedIn: 'root'
})
export class RequestLogService {
  private requestLogsSubject = new BehaviorSubject<RequestLog[]>([]);
  private statsSubject = new BehaviorSubject<RequestStats>({
    totalRequests: 0,
    successRequests: 0,
    errorRequests: 0,
    averageDuration: 0,
    lastRequestTime: ''
  });

  /**
   * 请求记录流
   */
  public readonly requestLogs$ = this.requestLogsSubject.asObservable();

  /**
   * 统计信息流
   */
  public readonly stats$ = this.statsSubject.asObservable();

  /**
   * 获取当前请求记录
   */
  get requestLogs(): RequestLog[] {
    return this.requestLogsSubject.value;
  }

  /**
   * 获取当前统计信息
   */
  get stats(): RequestStats {
    return this.statsSubject.value;
  }

  /**
   * 添加请求记录
   */
  addRequest(request: RequestLog): void {
    const currentLogs = this.requestLogs;
    const newLogs = [request, ...currentLogs];
    
    // 限制记录数量
    if (newLogs.length > 100) {
      newLogs.splice(100);
    }
    
    this.requestLogsSubject.next(newLogs);
    this.updateStats(newLogs);
  }

  /**
   * 更新请求状态
   */
  updateRequestStatus(requestId: string, status: number, response: any, duration?: number, error?: string): void {
    const currentLogs = this.requestLogs;
    const requestIndex = currentLogs.findIndex(log => log.id === requestId);
    
    if (requestIndex !== -1) {
      const updatedLogs = [...currentLogs];
      updatedLogs[requestIndex] = {
        ...updatedLogs[requestIndex],
        status,
        response,
        duration: duration || updatedLogs[requestIndex].duration,
        error
      };
      
      this.requestLogsSubject.next(updatedLogs);
      this.updateStats(updatedLogs);
    }
  }

  /**
   * 清除所有请求记录
   */
  clearLogs(): void {
    this.requestLogsSubject.next([]);
    this.updateStats([]);
  }

  /**
   * 更新统计信息
   */
  private updateStats(logs: RequestLog[]): void {
    const totalRequests = logs.length;
    const successRequests = logs.filter(log => log.status >= 200 && log.status < 400).length;
    const errorRequests = logs.filter(log => log.status >= 400).length;
    const averageDuration = logs.length > 0 
      ? logs.reduce((sum, log) => sum + log.duration, 0) / logs.length 
      : 0;
    const lastRequestTime = logs.length > 0 ? logs[0].timestamp : '';

    this.statsSubject.next({
      totalRequests,
      successRequests,
      errorRequests,
      averageDuration: Math.round(averageDuration),
      lastRequestTime
    });
  }

  /**
   * 生成请求ID
   */
  generateRequestId(): string {
    return 'req_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  }

  /**
   * 格式化请求头
   */
  formatHeaders(headers: any): { [key: string]: string } {
    const formatted: { [key: string]: string } = {};
    
    if (headers && typeof headers === 'object') {
      Object.keys(headers).forEach(key => {
        formatted[key] = String(headers[key]);
      });
    }
    
    return formatted;
  }

  /**
   * 格式化请求体
   */
  formatBody(body: any): any {
    if (body === null || body === undefined) {
      return null;
    }
    
    if (typeof body === 'string') {
      try {
        return JSON.parse(body);
      } catch {
        return body;
      }
    }
    
    return body;
  }
}
